package com.boby.homecamera.activity.server

import android.Manifest
import android.app.ActivityOptions
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.view.View
import android.view.WindowInsetsController
import android.widget.EditText
import android.widget.TextView

import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SwitchCompat
import androidx.appcompat.widget.Toolbar
import androidx.core.app.ActivityCompat
import com.boby.homecamera.R
import com.boby.homecamera.activity.LauncherActivity
import com.boby.homecamera.config.AppConfig
import com.boby.homecamera.constant.Constant
import com.boby.homecamera.db.DBManager
import com.boby.homecamera.util.JwtUtil
import com.boby.lib_common.base.BaseActivity
import com.boby.lib_common.extens.toast

class InitServerActivity : BaseActivity() {
    private val permissions: Array<String>
    init {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            permissions = arrayOf(
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CAMERA,
                Manifest.permission.FOREGROUND_SERVICE,
                Manifest.permission.FOREGROUND_SERVICE_CAMERA,
                Manifest.permission.FOREGROUND_SERVICE_MICROPHONE,
                Manifest.permission.POST_NOTIFICATIONS
            )
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            permissions = arrayOf(
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CAMERA,
                Manifest.permission.FOREGROUND_SERVICE
            )
        } else {
            permissions = arrayOf(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA)
        }
    }
    private lateinit var et_user_name: EditText
    private lateinit var et_user_password: EditText
    private lateinit var tv_token_time1: TextView
    private lateinit var tv_token_time2: TextView
    private lateinit var tv_token_time3: TextView
    private lateinit var tv_resolution_540: TextView
    private lateinit var tv_resolution_720: TextView
    private lateinit var tv_resolution_1080: TextView
    private lateinit var tv_camera_front: TextView
    private lateinit var tv_camera_back: TextView
    private lateinit var tv_bitrate_1: TextView
    private lateinit var tv_bitrate_2: TextView
    private lateinit var sw_audio_detect: SwitchCompat
    private lateinit var sw_person_detect: SwitchCompat

    private var tokenTime = 7
    private var resolution = 720
    private var bitrate = 1
    private var cameraId = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_init_server)
        val toolbar: Toolbar = findViewById(R.id.mToolbar)
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true) // 显示返回按钮
        initToolBar(toolbar)
        initView()
        initData()
    }
    private fun initView(){
        et_user_name =  findViewById(R.id.et_user_name)
        et_user_password =  findViewById(R.id.et_user_password)
        tv_token_time1 =  findViewById(R.id.tv_token_time1)
        tv_token_time2 =  findViewById(R.id.tv_token_time2)
        tv_token_time3 =  findViewById(R.id.tv_token_time3)
        tv_resolution_540 =  findViewById(R.id.tv_resolution_540)
        tv_resolution_720 =  findViewById(R.id.tv_resolution_720)
        tv_resolution_1080 =  findViewById(R.id.tv_resolution_1080)
        tv_bitrate_1 =  findViewById(R.id.tv_bitrate_1)
        tv_bitrate_2 =  findViewById(R.id.tv_bitrate_2)
        tv_camera_front =  findViewById(R.id.tv_camera_front)
        tv_camera_back =  findViewById(R.id.tv_camera_back)
        sw_audio_detect =  findViewById(R.id.sw_audio_detect)
        sw_person_detect =  findViewById(R.id.sw_person_detect)

        tv_token_time1.setOnClickListener {
            setTokenTime(1)
        }
        tv_token_time2.setOnClickListener {
            setTokenTime(7)
        }
        tv_token_time3.setOnClickListener {
            setTokenTime(365)
        }
        tv_resolution_540.setOnClickListener {
            setResolution(540)
        }
        tv_resolution_720.setOnClickListener {
            setResolution(720)
        }
        tv_resolution_1080.setOnClickListener {
            setResolution(1080)
        }
        tv_camera_front.setOnClickListener {
            setCamera(1)
        }
        tv_camera_back.setOnClickListener {
            setCamera(0)
        }
        tv_bitrate_1.setOnClickListener {
            setBitrate(1)
        }
        tv_bitrate_2.setOnClickListener {
            setBitrate(2)
        }
    }

    private fun initData(){
        et_user_name.setText(AppConfig.userName)
        et_user_password.setText(AppConfig.userPassword)
        setTokenTime(AppConfig.tokenTime)
        setResolution(AppConfig.videoResolution)
        setBitrate(AppConfig.videoBitrate)
        setCamera(AppConfig.videoCameraId)
        sw_audio_detect.isChecked = AppConfig.isDetectAudioEvent == true
        sw_person_detect.isChecked = AppConfig.isDetectPersonEvent == true
    }

    private fun setTokenTime(time:Int){
        tokenTime = time
        tv_token_time1.isSelected = time == 1
        tv_token_time2.isSelected = time == 7
        tv_token_time3.isSelected = time == 365
    }
    private fun setResolution(resolution:Int){
        this.resolution = resolution
        tv_resolution_540.isSelected = resolution == 540
        tv_resolution_720.isSelected = resolution == 720
        tv_resolution_1080.isSelected = resolution == 1080
    }
    private fun setBitrate(bitrate:Int){
        this.bitrate = bitrate
        tv_bitrate_1.isSelected = bitrate == 1
        tv_bitrate_2.isSelected = bitrate == 2
    }
    private fun setCamera(cameraId:Int){
        this.cameraId = cameraId
        tv_camera_front.isSelected = cameraId == 1
        tv_camera_back.isSelected = cameraId == 0
    }

    fun startServer(view: View) {
        val userName = et_user_name.text.toString()
        val password = et_user_password.text.toString()
        if(userName.isEmpty()){
            toast("请输入登录账号")
            return
        }
        if(password.isEmpty()){
            toast("请输入登录密码")
            return
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) {
            val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
            intent.setData(Uri.parse("package:" + this.packageName))
            startActivityForResult(intent, 0)
            return
        }
        if (!hasPermissions(this, *permissions)) {
            ActivityCompat.requestPermissions(this, permissions, 1)
        } else {
            if(AppConfig.userPassword != password || AppConfig.userName != userName){
                JwtUtil.updateKey()
            }
            AppConfig.userName = userName
            AppConfig.userPassword = password
            AppConfig.tokenTime = tokenTime
            AppConfig.videoResolution = resolution
            AppConfig.videoBitrate = bitrate
            AppConfig.videoCameraId = cameraId
            JwtUtil.setTokenExpiration(tokenTime)
            AppConfig.Record.setResolution(resolution)
            AppConfig.isDetectAudioEvent = sw_audio_detect.isChecked
            AppConfig.isDetectPersonEvent = sw_person_detect.isChecked
            DBManager.instance.init()
            startActivity(Intent(this,ServerHomeActivity::class.java))
            finish()
        }


    }

    override fun onSupportNavigateUp(): Boolean {
        AppConfig.deviceModel = Constant.DEVICE_MODEL_UNSELECT
        val option = ActivityOptions.makeCustomAnimation(this, com.boby.lib_common.R.anim.slide_in_left, com.boby.lib_common.R.anim.slide_out_right)
        startActivity(Intent(this, LauncherActivity::class.java),option.toBundle())
        finish()
        return true
    }

    private fun hasPermissions(context: Context?, vararg permissions: String): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null) {
            for (permission in permissions) {
                if (ActivityCompat.checkSelfPermission(
                        context,
                        permission
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    return false
                }
            }
        }
        return true
    }


}